# coding:utf-8

import tornado.web
import tornado.ioloop
import tornado.options
import tornado.httpserver
import json
import os

from tornado.options import options
from tornado.web import RequestHandler, StaticFileHandler

tornado.options.define("port", default=8000, type=int, help="run server on the given port")


class BaseHandler(RequestHandler):
    """请求处理基类"""
    def prepare(self):
        if self.request.headers.get("Content-Type", "").startswith("application/json"):
            try:
                self.json_args = json.loads(self.request.body)
            except Exception as e:
                self.json_args = {}

def title_join(t1, t2):
    return "+".join([t1, t2])

class IndexHandler(BaseHandler):
    """请求处理类"""
    def get(self):
        houses = [
            {
                "price": 398,
                "title1": "宽窄巷子",
                "title2": "文化保护区双地铁",
                "score": 5,
                "comments": 6,
                "position": "北京市丰台区六里桥地铁"
            },
            # {
            #     "price": 398,
            #     "title": "宽窄巷子+160平大空间+文化保护区双地铁",
            #     "score": 5,
            #     "comments": 6,
            #     "position": "北京市丰台区六里桥地铁"
            # },
            # {
            #     "price": 398,
            #     "title": "宽窄巷子+160平大空间+文化保护区双地铁",
            #     "score": 5,
            #     "comments": 6,
            #     "position": "北京市丰台区六里桥地铁"
            # },
            # {
            #     "price": 398,
            #     "title": "宽窄巷子+160平大空间+文化保护区双地铁",
            #     "score": 5,
            #     "comments": 6,
            #     "position": "北京市丰台区六里桥地铁"
            # },
            # {
            #     "price": 398,
            #     "title": "宽窄巷子+160平大空间+文化保护区双地铁",
            #     "score": 5,
            #     "comments": 6,
            #     "position": "北京市丰台区六里桥地铁"
            # }
            ]
        self.render("index.html", houses=houses, fun_title_join=title_join)

class FormHandler(BaseHandler):
    """"""
    def get(self):
        self.render("test.html", text="")

    def post(self):
        text = self.get_argument("text", "")
        self.set_header("X-XSS-Protection", 0)
        self.render("test.html", text=text)

if __name__ == "__main__":
    tornado.options.parse_command_line()

    settings = {
        "debug": True,
        "static_path": os.path.join(os.path.dirname(__file__), "statics"),
        "template_path": os.path.join(os.path.dirname(__file__), "template")
    }
    app = tornado.web.Application(
        [
            # (r"/", IndexHandler),
            (r"/", FormHandler),
            (r"/(.*)", StaticFileHandler,
             {"path": os.path.join(os.path.dirname(__file__), "statics/html"),
              "default_filename": "index.html"})
        ],
        **settings
    )
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.current().start()